﻿using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Yuebon.Security.Services
{
    public class LicenseService:BaseService<SysLicense, LicenseModel>,ILicenseService
    {        
        
        private ILicenseRepository _licenseRepository;

        public LicenseService(ILicenseRepository licenseRepository)
        {
            _licenseRepository = licenseRepository;            
        }

        public async Task<Tuple<bool,string>> ValidateLicenseAsync(string licenseKey,string hardInfo)
        {
            try
            {
                if (string.IsNullOrEmpty(hardInfo)) {
                    return new Tuple<bool, string>(false, "参数硬件码缺失");
                }

                if (string.IsNullOrEmpty(licenseKey)) {

                    return new Tuple<bool, string>(false, "请联系管理员获取授权码，QQ:328283433,微信:xinfei_aaron,添加请注明授权");
                }


                var license = _licenseRepository.GetListWhere($"LicenseKey='{licenseKey}'").FirstOrDefault();
                if (license == null) {
                    return new Tuple<bool, string>(false, "无效授权码");
                }

                //如果授权码的硬件码为空，则将当前硬件码更新到授权表
                if ( string.IsNullOrEmpty(license.HardInfo))
                {
                    license.HardInfo = hardInfo;
                    _licenseRepository.Update(license);
                }

                if (license.HardInfo != hardInfo) {
                    return new Tuple<bool, string>(false, "该授权码已与其它硬件码绑定，请联系管理员获取授权码，QQ:328283433,微信:xinfei_aaron,添加请注明授权");
                }  

                if (license.ExpireDate < DateTime.Now)
                {
                    return new Tuple<bool, string>(false, "该授权码已已过期，请联系管理员获取授权码，QQ:328283433,微信:xinfei_aaron,添加请注明授权");
                }

                return new Tuple<bool, string>(true, "ok");
            }
            catch (Exception ex)
            {
                return new Tuple<bool, string>(false, ex.Message);
            }
        }

       

       
    }
}
